function [teststat_n,teststat_all,p_all] = Bootstrapped_Test(x1,x2,Nit,subsample_length,test)
%%%% This function conducts a simple bootstrap exercise (without
%%%% replacement) and the corresponding test (KS-test or paired t-test)

% bootstrapped distribution
nk  = ceil(subsample_length*length(x1));
teststat_n = zeros(Nit,1);

for i = 1:Nit
   k = randperm(length(x1));
   xx1 = x1(k(1:nk)); 
   xx2 = x2(k(1:nk));
   
   if test == 1 % kstest
   [~,~,stat] = kstest2(xx1,xx2);
        if i == 1
           [~,p_all,teststat_all] = kstest2(x1,x2);
        end
   elseif test == 2 % paired t-test
   [~,~,~,stat] = ttest(xx1,xx2);   
   stat = stat.tstat;
        if i == 1
           [~,~,~,stat_all] = ttest(xx1,xx2);   
           stat_all = stat_all.tstat; 
        end
   end
   
   teststat_n(i) = stat;
   
   clear k xx1 xx2 stat;
end


end

